import { NavigationGuardNext, RouteLocationNormalized } from 'vue-router';
import { HOME_PATH, LOGIN_PATH } from '@/model/path';
import { AUTH_TOKEN_NAME } from '@/config';

const routerGuard = (
  to: RouteLocationNormalized,
  from: RouteLocationNormalized,
  next: NavigationGuardNext
) => {
  if (to.path === LOGIN_PATH) {
    const auth_token: string | null =
      window.localStorage.getItem(AUTH_TOKEN_NAME);
    auth_token ? next(HOME_PATH) : next(); // 若进入的页面是登录页，且已存在token，直接重定向至HOME页面
  }
  const requiresAuth: boolean | unknown = to.meta.requiresAuth;
  requiresAuth === undefined && next(LOGIN_PATH); // 若为未定义页面，重定向到登录页
  if (requiresAuth) {
    const auth_token: string | null =
      window.localStorage.getItem(AUTH_TOKEN_NAME);
    !auth_token ? next(LOGIN_PATH) : next(); // 若无auth_token，直接重定向至登录页
  } else {
    next();
  }
  // 其他情况放行
};

export { routerGuard };
